package com.sanri.tools.modules.httpbind;

import com.alibaba.fastjson.JSON;
import com.sanri.tools.modules.core.exception.ToolException;
import com.sanri.tools.modules.core.service.cc.CommonConfigService;
import com.sanri.tools.modules.proxy.service.HttpFileManager;
import com.sanri.tools.modules.proxy.service.ProxyHttpService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

@Service
@Slf4j
public class HttpBindCCService {

    public static final String MODULE = "httpbind.conf";

    @Autowired
    private CommonConfigService commonConfigService;

    @Autowired
    private HttpFileManager httpFileManager;

    @Autowired
    private ProxyHttpService proxyHttpService;

    @Autowired
    private ApplicationContext applicationContext;

    /**
     * 代理绑定请求
     * @param proxyBindHttpParam
     * @param response
     * @throws IOException
     */
    public void proxy(ProxyBindHttpParam proxyBindHttpParam, HttpServletResponse response) throws IOException {
        String key = proxyBindHttpParam.getKey();
        String configFileName = proxyBindHttpParam.getConfigFileName();
        Map<String, HttpBindDto> configs = configs(configFileName);
        // 查询第一个是否为认证请求
        HttpBindDto firstHttpBind = configs.values().iterator().next();
        if (firstHttpBind.isAuthorization()){
            // 先发送第一个请求
            CloseableHttpResponse closeableHttpResponse = httpFileManager.sendRequest(firstHttpBind.getHttpConnName(), firstHttpBind.getReqId(), proxyBindHttpParam.getParams());
            closeableHttpResponse.close();
        }

        HttpBindDto httpBindDto = configs.get(key);
        if (httpBindDto == null){
            log.debug("没有找到绑定:{}",key);
            throw new ToolException("没有找到绑定:"+key);
        }
        CloseableHttpResponse closeableHttpResponse = httpFileManager.sendRequest(httpBindDto.getHttpConnName(), httpBindDto.getReqId(), proxyBindHttpParam.getParams());
        proxyHttpService.copyResponse(closeableHttpResponse,response);
    }

    /**
     * 解析绑定配置
     * @param configFileName 配置文件名
     * @return
     */
    public Map<String,HttpBindDto> configs(String configFileName) throws IOException {
        String content = commonConfigService.readTemplateFileContent(MODULE, configFileName);

        Map<String,HttpBindDto> httpBindDtoMap = new LinkedHashMap<>();

        String[] lines = StringUtils.split(content.trim(), "\n");
        for (String line : lines) {
            String lineTrim = StringUtils.trim(line);
            if (StringUtils.isBlank(lineTrim)){
                continue;
            }
            if (lineTrim.startsWith("#")){
                continue;
            }
            String[] items = StringUtils.split(lineTrim, ":");
            if (items.length < 4){
                log.warn("[{}]配置格式不正确: {}",configFileName,lineTrim);
                continue;
            }
            String key = StringUtils.trim(items[0]);
            String httpConnName = StringUtils.trim(items[1]);
            String reqId = StringUtils.trim(items[2]);
            String comment = StringUtils.trim(items[3]);

            HttpBindDto httpBindDto = new HttpBindDto(key, httpConnName, reqId, comment);
            if (items.length > 4){
                httpBindDto.setAuthorization(items[4]);
            }
            httpBindDtoMap.put(key,httpBindDto);
        }

        return httpBindDtoMap;
    }
}
